package com.hxzy.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hxzy.shop.config.oauth.SecurityUser;
import com.hxzy.shop.constant.AuthConstant;
import com.hxzy.shop.dto.UserDto;
import com.hxzy.shop.entity.AdminAccount;
import com.hxzy.shop.entity.BackAccount;
import com.hxzy.shop.entity.Store;
import com.hxzy.shop.entity.StoreAccount;
import com.hxzy.shop.mapper.AccountMapper;
import com.hxzy.shop.mapper.BackAccountMapper;
import com.hxzy.shop.mapper.StoreAccountMapper;
import com.hxzy.shop.mapper.StoreMapper;
import com.hxzy.shop.vo.ApiException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 功能描述： 自定义登录认证(spring security框架)
 *
 * @author tonneyyy
 */
@Service
public class UserDetailsImpl implements UserDetailsService {
    @Resource
    private HttpServletRequest request;

    /**
     * 账户操作(AdminAccount表)
     */
    @Resource
    private AccountMapper accountMapper;

    /**
     * 门店信息
     */
    @Resource
    private StoreMapper storeMapper;

    /**
     * 门店账户表
     */
    @Resource
    private StoreAccountMapper storeAccountMapper;

    /**
     * 总部账户表
     */
    @Resource
    private BackAccountMapper backAccountMapper;

    /**
     * 登录并授权
     * @param account
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        // client_id=[Admin后台管理, Admin_Slave 后台分店管理, back_admin 总端后台]
        String clientId = request.getParameter("client_id");
        UserDto userDto = null;
        if (AuthConstant.ADMIN_CLIENT_ID.equals(clientId)) {
            //Admin后台管理
            AdminAccount acc = accountMapper.findAccountByAccount(account);

            if (!ObjectUtil.isEmpty(acc)) {
                userDto = new UserDto();
                userDto.setId(acc.getId());
                userDto.setUser_name(acc.getAccount());
                userDto.setPassword(acc.getPassword());
                userDto.setState(acc.getState());
                userDto.setClient_id(clientId);
                userDto.setMerchantId(acc.getMerchantId());
            }
        } else if (AuthConstant.ADMIN_SLAVE_CLIENT_ID.equals(clientId)) {
            //后台分店管理
            StoreAccount storeAccount = storeAccountMapper.selectOne(new LambdaQueryWrapper<StoreAccount>().eq(StoreAccount::getAccount,account));
            if (!ObjectUtil.isEmpty(storeAccount)) {
                Store store = storeMapper.selectById(storeAccount.getStoreId());
                userDto = new UserDto();
                userDto.setId(storeAccount.getId());
                userDto.setUser_name(storeAccount.getAccount());
                userDto.setPassword(storeAccount.getPassword());
                userDto.setState(store.getState());
                userDto.setClient_id(clientId);
                userDto.setStoreId(store.getId());
                userDto.setMerchantId(store.getMerchantId());
            }
        } else if (AuthConstant.BACK_ADMIN_CLIENT_ID.equals(clientId)){
            //todo 总部端后台
            BackAccount backAccount = backAccountMapper.selectOne(new LambdaQueryWrapper<BackAccount>().eq(BackAccount::getAccount, account));
            if (!ObjectUtil.isEmpty(backAccount)) {
                userDto = new UserDto();
                userDto.setId(backAccount.getId());
                userDto.setUser_name(backAccount.getAccount());
                userDto.setPassword(backAccount.getPassword());
                userDto.setState(backAccount.getState());
                userDto.setClient_id(clientId);
            }
        }else {
            throw new ApiException(500, "未知异常");
        }
        if (null == userDto) {
            throw new UsernameNotFoundException("帐号或密码错误");
        }
        SecurityUser securityUser = new SecurityUser(userDto);
        if (!securityUser.isEnabled()) {
            throw new DisabledException("该账户已被禁用，请联系管理员");
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException("该账号已被锁定，请联系管理员");
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException("该账号已过期，请联系管理员");
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException("该账户的登录凭证已过期，请重新登录");
        }
        return securityUser;
    }
}
